//
//  UserInfoDao.m
//  JiaoX
//
//  Created by yinqy on 15/3/10.
//  Copyright (c) 2015年 北京娇羞科技有限公司. All rights reserved.
//

#import "UserInfoDao.h"
#import "FMDatabase.h"
#import "UserInfo.h"

#define TABLENAME @"TB_USER_INFO"

@interface UserInfoDao()
{
    FMDatabase *db;
    NSString *database_path;
}

@end
@implementation UserInfoDao
- (instancetype)init
{
    self = [super init];
    if (self) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documents = [paths objectAtIndex:0];
        database_path = [documents stringByAppendingPathComponent:DB_NAME];
        db = [FMDatabase databaseWithPath:database_path];
        
        [self createTable];
    }
    return self;
}

/**
 *  创建表
 */
- (void)createTable{
    //sql 语句
    if ([db open]) {
                NSString *sql =  [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' (_id integer primary key autoincrement,userId varchar(63),userInfo blob,key1 varchar(100),key2 varchar(100),key3 varchar(100),key4 varchar(100),key5 varchar(100))",TABLENAME];
        BOOL res = [db executeUpdate:sql];
        if (!res) {
            JXLog(@"error when creating db table");
        } else {
            JXLog(@"success to creating db table");
        }
        [db close];
    }
}

-(BOOL)setUserInfo:(UserInfo *)userInfo{
    NSDictionary *dic = [userInfo keyValues];
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dic];
    if ([db open]) {
        //再添加新数据
        BOOL res = [db executeUpdate:@"INSERT INTO TB_USER_INFO (userId,userInfo) VALUES (?,?);",userInfo.userId,data];
        if (!res) {
            JXLog(@"error when insert db table");
        } else {
            JXLog(@"success to insert db table");
        }
        [db close];
        return res;
    }
    return NO;
}

-(UserInfo *)getUserInfoWithId:(NSString *)userId{
    if ([db open]) {
        NSString *sql = [NSString stringWithFormat:@"SELECT * FROM %@ WHERE userId = %@",TABLENAME,userId];
        FMResultSet * rs = [db executeQuery:sql];
        if ([rs next]) {
            NSData *userInfoData = [rs objectForColumnName:@"userInfo"];
            NSDictionary *userInfoDic = [NSKeyedUnarchiver unarchiveObjectWithData:userInfoData];
            UserInfo *userInfo = [UserInfo objectWithKeyValues:userInfoDic];
            return userInfo;
        }
    }
    return nil;
}


-(BOOL)deleteUserInfoWithId:(NSString *)userId{
    if ([db open]) {
        BOOL result = [db executeUpdate:@"DELETE FROM %@ WHERE userId = %@",TABLENAME,userId];
        return result;
    }
    return NO;
}

@end
